package lion.dev.text;

import java.util.regex.Matcher;

import org.apache.commons.lang.StringUtils;

public class HtmlEscape {

	/**
	 * 替换所有html关键字
	 *
	 * @param src
	 * @return
	 */
	public static final String escape(String src) {

		if (src == null || src.length() <= 0) { return ""; }

		src = src.replace("<br>", "\n").replace("&nbsp;", " ").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#39;")
				.replace("  ", "&nbsp; ").replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;").replace("\r", "");

		return src;
	}

	public static final String escapeWithoutBr(String src) {

		if (src == null || src.length() <= 0) { return ""; }
		return escape(src).replaceAll("\n", "<br>");
	}

	public static final String unescape(String src) {

		if (src == null || src.trim().length() <= 0) { return ""; }

		return src.replace("\n", "<br>").replace(" ", "&nbsp;").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'");
	}

	/**
	 * 替换所有脚本中的内容，此内容用来初始化文本域的内容
	 *
	 * @param src
	 * @return
	 */
	public static final String escapeInlineScriptValue(String src) {

		if (src == null || src.length() <= 0) { return ""; }

		src = src.replace("\\", Matcher.quoteReplacement("\\")).replace("\n", Matcher.quoteReplacement("\n")).replace("\r", "").replace("'", Matcher.quoteReplacement("\'"))
				.replace("\"", Matcher.quoteReplacement("\""));

		return src;
	}

	/**
	 * 去掉html页面里的标签
	 */
	public static String stripTag(String src) {

		if (StringUtils.isEmpty(src)) { return ""; }

		src = src.replace("<b>", " ").replace("</b>", " ").replace("<strong>", " ").replace("</strong>", " ").replaceAll("<.+?>", "");

		return src;
	}

	/**
	 * 去掉html头尾,脚本，样式，标签
	 */
	public static String stripHtml(String src) {

		if (StringUtils.isBlank(src)) { return ""; }

		StringBuilder sbu = new StringBuilder(src);
		// 去头尾
		int idx = sbu.indexOf("<body");
		if (idx > 0) {
			sbu.delete(0, sbu.indexOf(">", idx) + 1);
		}
		idx = sbu.lastIndexOf("</body");
		if (idx > 0) {
			sbu.delete(idx, sbu.length());
		}

		// 去脚本
		idx = sbu.indexOf("<script");
		while (idx > 0) {
			sbu.delete(idx, sbu.indexOf("</script>", idx) + 9);
			idx = sbu.indexOf("<script");
		}
		// 去脚本
		idx = sbu.indexOf("<noscript");
		while (idx > 0) {
			sbu.delete(idx, sbu.indexOf("</noscript>", idx) + 11);
			idx = sbu.indexOf("<noscript");
		}
		// 去样式
		idx = sbu.indexOf("<style");
		while (idx > 0) {
			sbu.delete(idx, sbu.indexOf("</style>", idx) + 1);
			idx = sbu.indexOf("<style");
		}

		// 去标签
		return sbu.toString().replaceAll("<.+?>", "").replaceAll("\n{3,}", "\n\n").trim();
	}

	public static String summary(String src, int len) {

		if (StringUtils.isBlank(src)) { return ""; }

		return StringUtils.left(stripHtml(src).replaceAll("(&nbsp;)+", " ").replaceAll("\\s{3,}", " "), len);
	}

}
